/**
 * 交易对监控模块
 * 核心监控逻辑，支持多交易所
 */

const ExchangeFactory = require('../services/exchangeFactory');
const EmailService = require('../services/emailService');
const storage = require('../utils/storage');
const logger = require('../utils/logger');

class TradingPairMonitor {
  constructor() {
    this.exchangeFactory = new ExchangeFactory();
    this.emailService = new EmailService();
    this.isRunning = false;
    this.intervalId = null;
    this.enabledExchanges = [];
  }

  /**
   * 初始化监控器
   */
  async initialize() {
    logger.info('🚀 多交易所交易对监控系统启动');
    
    // 从环境变量读取启用的交易所
    const enabledExchangesStr = process.env.ENABLED_EXCHANGES || 'upbit,binance';
    this.enabledExchanges = enabledExchangesStr.split(',').map(ex => ex.trim());
    
    // 初始化交易所工厂
    this.exchangeFactory.initialize(this.enabledExchanges);
    
    // 显示监控配置
    logger.debug(`📧 邮件接收者: ${this.emailService.getRecipients().join(', ')}`);
    logger.debug(`⏰ 检查间隔: ${this.emailService.getCheckInterval() / 1000} 秒`);
    logger.info(`🏪 启用的交易所: ${this.enabledExchanges.join(', ')}`);
    
    // 验证邮件配置
    const emailValid = await this.emailService.verifyConfig();
    if (!emailValid) {
      logger.warn('邮件配置不完整，新增交易对信息将只在控制台显示');
      logger.info('💡 要启用邮件通知，请配置 .env 文件中的邮件设置');
    }

    // 检查交易所连接状态
    logger.debug('🔗 检查交易所连接状态...');
    const connectionResults = await this.exchangeFactory.checkAllConnections();
    for (const [exchangeId, result] of Object.entries(connectionResults)) {
      if (result.connected) {
        logger.debug(`✅ ${result.name} 连接正常`);
      } else {
        logger.warn(`⚠️  ${result.name} 连接失败${result.error ? `: ${result.error}` : ''}`);
      }
    }

    // 首次获取交易对数据
    await this.checkTradingPairs();
    
    logger.success('多交易所监控系统初始化完成');
  }

  /**
   * 开始监控
   */
  start() {
    if (this.isRunning) {
      logger.warn('监控系统已在运行中');
      return;
    }

    this.isRunning = true;
    const interval = this.emailService.getCheckInterval();
    
    this.intervalId = setInterval(() => {
      this.checkTradingPairs();
    }, interval);
    
    logger.info('📊 开始定期监控...');
  }

  /**
   * 停止监控
   */
  stop() {
    if (!this.isRunning) {
      logger.warn('监控系统未在运行');
      return;
    }

    this.isRunning = false;
    
    if (this.intervalId) {
      clearInterval(this.intervalId);
      this.intervalId = null;
    }
    
    logger.info('👋 监控系统已停止');
  }

  /**
   * 检查交易对变化
   */
  async checkTradingPairs() {
    const startTime = new Date();
    let overallSuccess = false;
    let exchangeResults = {};
    let allNewPairs = [];

    try {
      logger.debug('🔍 开始检查多交易所交易对变化...');
      
      // 获取所有交易所的当前交易对数据
      const currentExchangeData = await this.exchangeFactory.fetchAllTradingPairs();
      
      if (Object.keys(currentExchangeData).length === 0) {
        logger.warn('未获取到任何交易所数据，跳过本次检查');
        storage.logMonitorActivity({
          timestamp: startTime.toISOString(),
          exchanges: {},
          totalNewPairs: 0,
          allNewPairs: [],
          success: false,
          error: '未获取到任何交易所数据',
          checkDuration: new Date() - startTime
        });
        return;
      }

      // 为每个交易所检查新增交易对
      for (const [exchangeId, currentData] of Object.entries(currentExchangeData)) {
        const exchangeName = this.exchangeFactory.exchanges.get(exchangeId)?.name || exchangeId;
        
        exchangeResults[exchangeId] = {
          name: exchangeName,
          success: currentData.success,
          totalPairs: currentData.count,
          newPairs: [],
          error: currentData.error || null
        };

        if (!currentData.success) {
          logger.error(`❌ ${exchangeName}: ${currentData.error}`);
          continue;
        }

        // 从存储读取上次的数据
        const previousPairs = storage.loadPreviousPairs(exchangeId);

        if (previousPairs.size === 0) {
          logger.debug(`📝 初始化 ${exchangeName} 交易对数据`);
          storage.savePairs(currentData.pairs, exchangeId);
          exchangeResults[exchangeId].note = '系统初始化';
          continue;
        }

        // 找出新增的交易对
        const newPairs = [...currentData.pairs].filter(pair => !previousPairs.has(pair));
        exchangeResults[exchangeId].newPairs = newPairs;

        if (newPairs.length > 0) {
          logger.success(`🎉 ${exchangeName}: 发现 ${newPairs.length} 个新交易对`);
          logger.info(`   新增: ${newPairs.slice(0, 5).join(', ')}${newPairs.length > 5 ? '...' : ''}`);
          
          // 添加到总的新增列表，标记来源交易所
          const taggedNewPairs = newPairs.map(pair => ({
            pair: pair,
            exchange: exchangeId,
            exchangeName: exchangeName
          }));
          allNewPairs.push(...taggedNewPairs);
          
          // 保存更新后的交易对数据
          storage.savePairs(currentData.pairs, exchangeId);
        } else {
          logger.debug(`${exchangeName}: 没有发现新的交易对`);
        }
      }

      // 发送邮件通知（如果有新增交易对）
      if (allNewPairs.length > 0) {
        await this.emailService.sendNewPairsNotification(allNewPairs);
      }

      // 检查是否至少有一个交易所成功
      overallSuccess = Object.values(exchangeResults).some(result => result.success);

      // 显示检查摘要
      const successCount = Object.values(exchangeResults).filter(r => r.success).length;
      const totalCount = Object.keys(exchangeResults).length;
      if (allNewPairs.length > 0) {
        logger.info(`📊 检查完成: ${successCount}/${totalCount} 个交易所成功，共发现 ${allNewPairs.length} 个新交易对`);
      } else {
        logger.debug(`📊 检查完成: ${successCount}/${totalCount} 个交易所成功，无新增交易对`);
      }

    } catch (err) {
      const error = err.message;
      logger.error(`多交易所监控过程出错: ${error}`);
      
      storage.logMonitorActivity({
        timestamp: startTime.toISOString(),
        exchanges: exchangeResults,
        totalNewPairs: allNewPairs.length,
        allNewPairs: allNewPairs,
        success: false,
        error: error,
        checkDuration: new Date() - startTime
      });
      return;
    }

    // 记录监控活动日志
    storage.logMonitorActivity({
      timestamp: startTime.toISOString(),
      exchanges: exchangeResults,
      totalNewPairs: allNewPairs.length,
      allNewPairs: allNewPairs,
      success: overallSuccess,
      error: null,
      checkDuration: new Date() - startTime
    });
  }

  /**
   * 获取监控状态
   */
  getStatus() {
    return {
      isRunning: this.isRunning,
      checkInterval: this.emailService.getCheckInterval(),
      recipients: this.emailService.getRecipients(),
      dataFilePath: storage.getDataFilePath()
    };
  }

  /**
   * 手动触发一次检查
   */
  async triggerCheck() {
    logger.info('🔍 手动触发交易对检查...');
    await this.checkTradingPairs();
  }
}

module.exports = TradingPairMonitor;
